package com.lzb.permanentcalendar.activity;

import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.lzb.permanentcalendar.BaseAc;
import com.lzb.permanentcalendar.R;
import com.lzb.permanentcalendar.adapter.FestivalAdapter;
import com.lzb.permanentcalendar.databinding.ActivityFestivalAssistantBinding;
import com.nlf.calendar.Lunar;
import com.nlf.calendar.LunarYear;
import com.nlf.calendar.Solar;
import com.othershe.calendarview.bean.JrBean;
import com.othershe.calendarview.utils.DateUtils;
import com.othershe.calendarview.utils.LunarUtil;
import com.othershe.calendarview.utils.SolarUtil;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class FestivalAssistantActivity extends BaseAc<ActivityFestivalAssistantBinding> implements View.OnClickListener {

    private int type = 0;
    private FestivalAdapter festivalAdapter;

    @Override
    protected int onCreate() {
        return R.layout.activity_festival_assistant;
    }

    @Override
    protected void initView() {
        mDataBinding.ivFestivalAssistantBack.setOnClickListener(view -> getOnBackPressedDispatcher().onBackPressed());

        mDataBinding.llFestival.setOnClickListener(this);
        mDataBinding.llSolarTerms.setOnClickListener(this);

        mDataBinding.rvFestivalList.setLayoutManager(new LinearLayoutManager(mContext));
        festivalAdapter = new FestivalAdapter();
        mDataBinding.rvFestivalList.setAdapter(festivalAdapter);
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.llFestival) {//节日
            clearSelection();
            mDataBinding.tvFestival.setTextColor(Color.parseColor("#AD2419"));
            mDataBinding.ivFestivalSel.setVisibility(View.VISIBLE);
            type = 0;
            getData();
        } else if (id == R.id.llSolarTerms) {//二十四节气
            clearSelection();
            mDataBinding.tvSolarTerms.setTextColor(Color.parseColor("#AD2419"));
            mDataBinding.ivSolarTermsSel.setVisibility(View.VISIBLE);
            type = 1;
            getData();
        }
    }

    @Override
    protected void initData() {
        getData();
    }

    private void getData() {
        List<JrBean> jqBeans = new ArrayList<JrBean>();
        Solar solar1 = Solar.fromDate(new Date());
        mDataBinding.tvYear.setText(solar1.getYear() + "年");
        if (type == 1) {
            LunarYear lunarYear = LunarYear.fromYear(solar1.getYear());
            List<Double> jieQiJulianDays = lunarYear.getJieQiJulianDays();
            for (int i = 0; i < jieQiJulianDays.size(); i++) {
                Solar solar = Solar.fromJulianDay(jieQiJulianDays.get(i));
                Lunar lunar = solar.getLunar();
                String ymd = solar.toYmd();
                if (ymd.contains("-")) {
                    String[] split = ymd.split("-");
                    if (split.length == 3) {
                        String year = split[0];
                        if (split[0].startsWith("0")) {
                            year = split[0].substring(1, split[0].length());
                        }
                        String mo = split[1];
                        if (split[1].startsWith("0")) {
                            mo = split[1].substring(1, split[1].length());
                        }
                        String day = split[2];
                        if (split[2].startsWith("0")) {
                            day = split[2].substring(1, split[2].length());
                        }
                        int days = (int) DateUtils.calculateDaysBetween(solar1.getYear() + "-" + solar1.getMonth() + "-" + solar1.getDay(),
                                year + "-" + mo + "-" + day);
                        jqBeans.add(new JrBean(lunar.getJieQi(), Integer.parseInt(year),
                                Integer.parseInt(mo), Integer.parseInt(day), days));
                    }
                }

            }
            festivalAdapter.setNewData(jqBeans);
        } else {
            Calendar selectedDate = Calendar.getInstance();
            ; // 注意月份从0开始
            findNextFestivals(selectedDate);
        }
    }

    private void findNextFestivals(Calendar startDate) {
        List<JrBean> festivals = new ArrayList<>();
        Calendar tempDate = (Calendar) startDate.clone();

        // 跳过起始日（用户可能不需要当天）
        while (festivals.size() < 26) {
            if (getFestivalName(tempDate) != null) {
                JrBean festivalName = getFestivalName(tempDate);
                int year = startDate.get(Calendar.YEAR);

                // 获取月份（注意：Calendar 的月份从 0 开始，实际需 +1）
                int month = startDate.get(Calendar.MONTH) + 1;
                // 获取日期（月份中的第几天）
                int day = startDate.get(Calendar.DAY_OF_MONTH);
                int days = (int) DateUtils.calculateDaysBetween(year + "-" + month + "-" + day,
                        festivalName.year + "-" + festivalName.mo + "-" + festivalName.day);
                festivalName.num = days;
                festivals.add(festivalName);
            }
            tempDate.add(Calendar.DAY_OF_MONTH, 1);
        }
        festivalAdapter.setNewData(festivals);
    }

    private JrBean getFestivalName(Calendar date) {
        int month = date.get(Calendar.MONTH) + 1;
        int day = date.get(Calendar.DAY_OF_MONTH);

        try {
            Solar solar = new Solar(date.get(Calendar.YEAR), month, day);
            // 转阴历
            Lunar lunar = solar.getLunar();
            String lunarHoliday = LunarUtil.getLunarHolidayTxt(lunar.toFullString());
            if (!TextUtils.isEmpty(lunarHoliday)) {
                JrBean jrBean = new JrBean();
                jrBean.setJrName(lunarHoliday);
                jrBean.year = date.get(Calendar.YEAR);
                jrBean.mo = month;
                jrBean.day = day;
                return jrBean;
            }
        } catch (Exception e) {
        }
        try {
            String solarHoliday = SolarUtil.getSolarHoliday(date.get(Calendar.YEAR), month, day);
            if (!TextUtils.isEmpty(solarHoliday)) {
                JrBean jrBean = new JrBean();
                jrBean.setJrName(solarHoliday);
                jrBean.year = date.get(Calendar.YEAR);
                jrBean.mo = month;
                jrBean.day = day;
                return jrBean;
            }
        } catch (Exception e) {

        }

        return null;
    }

    private void clearSelection() {
        mDataBinding.tvFestival.setTextColor(Color.parseColor("#999999"));
        mDataBinding.ivFestivalSel.setVisibility(View.GONE);
        mDataBinding.tvSolarTerms.setTextColor(Color.parseColor("#999999"));
        mDataBinding.ivSolarTermsSel.setVisibility(View.GONE);
    }
}